<template>
    <a-form :model="form" ref="formModel" :rules="formRules" :label-col="{ span: 6 }" :wrapper-col="{ span: 15 }">
        <a-form-item :label="$t('upperComputer.role.roleName')" name="displayName">
            <a-input v-model:value="form.displayName" :maxlength="50" />
        </a-form-item>
        <a-form-item :label="$t('upperComputer.role.roleCode')" name="code">
            <a-input v-model:value="form.code" :maxlength="50" :disabled="form.id ? true : false" />
        </a-form-item>
        <a-form-item :label="$t('upperComputer.role.description')" name="description">
            <a-textarea v-model:value="form.description" autoSize :maxlength="255" showCount />
        </a-form-item>
    </a-form>
</template>

<script setup lang='ts'>
import i18n from '@/i18n';
import { type FormInstance, message } from 'ant-design-vue';
import { type Ref, ref, onMounted } from 'vue';
import type { Rule } from 'ant-design-vue/lib/form';
import { getRoleApi, postRoleApi, putRoleApi } from '@/services/role';
import { RoleDto } from '@/models/role';

const props = defineProps<{ id: number }>();
defineExpose({ ok });

const form: Ref<RoleDto> = ref<RoleDto>(new RoleDto);
const formRef: Ref<FormInstance | undefined> = ref<FormInstance>();
const formRules: Record<string, Rule[]> = {
    code: [
        { required: true, trigger: 'blur', validator: codeValidator },
    ],
    displayName: [
        {
            required: true,
            max: 50,
            message: i18n.global.t('upperComputer.role.required.role'),
            trigger: 'blur',
        }
    ]
};

/**
 * code的正则验证
 * @param rule 
 * @param value 
 * @param callback 
 */
function codeValidator(rule: Rule, value: string, callback: Function): Promise<void> {
    const reg: RegExp = /^[A-Z][a-zA-Z]{1,49}$/;
    if (reg.test(value)) {
        return Promise.resolve();
    }
    return Promise.reject(i18n.global.t('upperComputer.role.required.code'));
}

onMounted(() => {
    getForm();
});

async function getForm(): Promise<void> {
    if (props.id) {
        form.value = await getRoleApi(props.id);
    }
}

async function ok(): Promise<boolean> {
    try {
        await formRef.value?.validate();
        if (props.id) {
            await putRoleApi(form.value);
        } else {
            await postRoleApi(form.value);
        }
        message.success(i18n.global.t('common.' + (props.id ? 'editSuccess' : 'addSuccess')));
        return true;
    } catch {
        return false;
    }
}
</script>